package org.fitweb.drivers;

import com.gargoylesoftware.htmlunit.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import java.util.ArrayList;
import java.util.List;

class AdaptedHtmlUnitDriver extends HtmlUnitDriver implements AdaptedWebDriver {
    private List<String> headersToClear = new ArrayList<String>();

    public AdaptedHtmlUnitDriver() {
        super(true); // Execute javascript

        getWebClient().setCssErrorHandler(new SilentCssErrorHandler());

        getWebClient().setIncorrectnessListener(new IncorrectnessListener() {
            public void notify(String message, Object source) {
                if (!message.contains("content type")) {
                    System.out.println("[HTMLUnit] " + message);
                }
            }
        });

        getWebClient().setAlertHandler(new AlertHandler() {
            public void handleAlert(Page page, String message) {
                System.out.println("[JavaScript Alert] " + message);
            }
        });
    }

    public WebClient underlyingWebClient() {
        return super.getWebClient();
    }

    @Override
    public void setCredentials(String username, String password) {
        DefaultCredentialsProvider credentialsProvider = new DefaultCredentialsProvider();
        credentialsProvider.addCredentials(username, password);
        getWebClient().setCredentialsProvider(credentialsProvider);
    }

    @Override
    public int getStatusCode() {
        return underlyingWebClient().getCurrentWindow().getEnclosedPage().getWebResponse().getStatusCode();
    }

    @Override
    public void setRequestHeader(String name, String value) {
        getWebClient().addRequestHeader(name, value);
        headersToClear.add(name);
    }

    @Override
    public void clearRequestHeaders() {
        for (String name : headersToClear) {
            getWebClient().removeRequestHeader(name);
        }
    }
}